import axios from 'axios'
import router from '@/router'
import iView from 'iview';
import store from '@/store'
import 'iview/dist/styles/iview.css'

axios.defaults.baseURL = '/api/'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
/**
 * 获取子页面的url（由于sips的token通过url传递）
 * */
let iframeSrc = document.URL
/**
 * 校验token是否存在
 * 存在放入sessionStorage
 * */
let pattern = /((?:\w|-)+)=((?:\w|-|\.)+)/ig;
let param = {}
iframeSrc.replace(pattern, function (a, b, c) {
    param[b] = c
})
if (param["token"]) {
    let loginToken=param["token"].toString()
    window.sessionStorage.setItem("token", loginToken)
}
let token=window.sessionStorage.getItem("token")
axios.defaults.headers.common['token']=token
// http request 拦截器
axios.interceptors.request.use(
    config => {
        if (localStorage.token) { // 判断token是否存在
            config.headers.Authorization = localStorage.token // 将token设置成请求头
            config.headers.Authorization = 123
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

// http response 拦截器
axios.interceptors.response.use(
    response => {
        // iView.Spin.hide()
        if (response.data.code === 403) {
            router.replace('/');
        }
        return response;
    },
    error => {
        return Promise.reject(error);
    }
);
window.httpCount = 0;
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function handleRequestPromise(url, params, loadingFlag) {
    return new Promise((resolve, reject) => {
        if (loadingFlag) {
            if (window.httpCount < 0) {
                window.httpCount = 0;
            }
            window.httpCount++;
            if (window.httpCount > 0) {
                store.commit('changeGlobalSpin', true);
            }
        }
         axios.get(url, {
            params: params
         }).then(res => {
             resolve(res);
             window.httpCount--;
             if (window.httpCount === 0) {
                 store.commit('changeGlobalSpin', false);
             }
         })
        .catch(err => {
                reject(err)
                window.httpCount--
                if (window.httpCount === 0) {
                    store.commit('changeGlobalSpin', false);
                }
         })
    });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function handleRequestPromisePost(url, params, loadingFlag) {
    return new Promise((resolve, reject) => {
        if (loadingFlag) {
            if (window.httpCount < 0) {
                window.httpCount = 0;
            }
            window.httpCount++;
            if (window.httpCount > 0) {
                store.commit('changeGlobalSpin', true);
            }
        }
        axios.post(url, params)
            .then(res => {
                resolve(res);
                window.httpCount--;
                if (window.httpCount === 0) {
                    store.commit('changeGlobalSpin', false);
                }
            })
            .catch(err => {
                reject(err)
                window.httpCount--
                if (window.httpCount === 0) {
                    store.commit('changeGlobalSpin', false);
                }
            })
    });
}

export default axios;
